package juc;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class SyncAndReentrantLockDemo {
	public static void main(String args[]){
		ShareData1 shareData1 = new ShareData1();
		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				shareData1.p1();
			}, "A").start();
			new Thread(() -> {
				shareData1.p3();
			}, "C").start();
			new Thread(() -> {
				shareData1.p2();
			}, "B").start();
		}
	}
}

class ShareData1 {
	private Lock lock = new ReentrantLock();
	private Condition c1 = lock.newCondition();
	private Condition c2 = lock.newCondition();
	private Condition c3 = lock.newCondition();
	Condition current = c1;

	public void p1() {
		lock.lock();
		try {
			while (current != c1) {
				c1.await();
			}
			for (int i = 0; i < 5; i++) {
				System.out.println(Thread.currentThread().getName() + "  " + i);
			}
			current = c2;
			current.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	public void p2() {
		lock.lock();
		try {
			while (current != c2) {
				c2.await();
			}
			for (int i = 0; i < 10; i++) {
				System.out.println(Thread.currentThread().getName() + "  " + i);
			}
			current = c3;
			current.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	public void p3() {
		lock.lock();
		try {
			while (current != c3) {
				c3.await();
			}
			for (int i = 0; i < 15; i++) {
				System.out.println(Thread.currentThread().getName() + "  " + i);
			}
			current = c1;
			current.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
}